package org.common.utils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

/**
 * 随机工具
 */
public class RandomUtils {


    public static ThreadLocalRandom getRandom() {
        return ThreadLocalRandom.current();
    }

    /**
     * 随机范围值
     * @param min >=
     * @param max <=
     */
    public static int getRandomInt(int min,int max){
        int abs = Math.abs(max - min) + 1;
        return (min + getRandom().nextInt(abs));
    }

    /**
     * 从集合中随机一个
     */
    public static <T> T selectOne(Collection<T> collection) {
        if (collection == null || collection.isEmpty()) {
            return null;
        }

        if (collection.size() == 1) {
            return collection.iterator().next();
        }

        int ran = getRandomInt(0, collection.size() - 1);
        if (collection instanceof List<T> list) {
            return list.get(ran);
        } else {
            int i = 0;
            for (T temp : collection) {
                if (i++ == ran) {
                    return temp;
                }
            }
        }

        return  null;
    }

    /**
     * 从集合中随机多个元素
     */
    public static <T> List<T> selectBatch(Collection<T> collection, int num) {
        if (collection.size() <= num) {
            return new ArrayList<>(collection);
        }

        List<T> ret = new ArrayList <>(num);
        List<T> curList = new LinkedList<>(collection);
        for (int i = 0; i < num; i++) {
            int ran = getRandomInt(0, curList.size() - 1);
            T hit = curList.remove(ran);
            ret.add(hit);
        }

        return ret;
    }
}
